//TODO: we need a function that generates various statement-related
//metadata, or maybe most of a statement, and fires it to the backend
//for instance, we include the current URL as the parent, and the
//current URL#qnumber as the activity.


var recordAttempt = function(tag, correct, skipped) { //TODO: any way to infer number of the question?
    $.post('/tincan/check_answers', {
        'question': tag,
        'success': correct || false, //make into boolean if omitted
        'skipped': skipped || false //ditto
    }); //don't care about results
};

var recordAssessmentCheck = function(score) {
    $.post('/tincan/assessment_check', {
        'score': score
    });
};


var recordWatching = function(video, duration, completion) {
    $.post('/tincan/watch_video', {
        'video': video,
        'duration': duration,
        'completion': completion || false
    });
};

//okay, add hook for youtube iframe JS API, then, for each
//video container iframe, ask to know about the state changed event
//every time state changes to not play, record difference from last
//time checked. Every time state changes to play, remember when.
//Also, watch out for reaching near the end of the video (recheck
//every second?) -- if so, or if the window closes, send the 
//completion for each video
//even better than watching for near end of video, check every, say
//hour. If video is playing, wait a little longer. 

var onYouTubeIframeAPIReady = function() {
    $(document).ready(function() {
        $('.video-container iframe').each(function() {
            var player;

            var totalWatched = 0;
            var lastVideoTime;
            var lastClockTime;
            var INTERVAL = 3000;
            var timer;

            function finishTiming(completion) {
                window.clearInterval(timer);
                recordWatching(player.getVideoUrl(), totalWatched, completion);
                totalWatched = 0; //in case they rewatch
                lastVideoTime = undefined;
                lastClockTime = undefined;
            }

            $(window).unload(function() {
                if(player && timer && totalWatched > 0) {
                    finishTiming(false);
                }
            });


            var onStateChange = function(event) {
                if(lastVideoTime == undefined
                        && event.data == YT.PlayerState.PLAYING) {
                    lastVideoTime = player.getCurrentTime();
                    lastClockTime = new Date().getTime();
                    //console.log('starting watching');
                    timer = window.setInterval(function() {
                        var newVideoTime = player.getCurrentTime();
                        var newClockTime = new Date().getTime();
                        var elapsedVideoTime = newVideoTime - lastVideoTime;
                        var elapsedClockTime = (newClockTime - lastClockTime) / 1000.0;

                        var elapsedCheck = Math.max(elapsedClockTime, INTERVAL / 1000.0) * 1.5

                        //console.log('Watched for ', elapsedVideoTime, ' checked against ', elapsedCheck);
                        if(elapsedVideoTime > 0
                                && elapsedVideoTime <= elapsedCheck) {
                            totalWatched += elapsedVideoTime;
                        }
                        lastVideoTime = newVideoTime;
                        lastClockTime = newClockTime;
                    }, INTERVAL);
                    //start timer here. It checks every small unit of time.
                    //if difference with last time looked at is
                    //small unit of time or less, add to time watched.
                    //otherwise, just reset last time checked

                } else if(event.data != YT.PlayerState.PLAYING) {
                    //good way to pause? don't worry about it for now
                }
                
                if(event.data == YT.PlayerState.ENDED && totalWatched > 0) {
                    finishTiming(true);
                }
            };

            player = new YT.Player(this, {
                'events': {
                    //'onReady': onReady,
                    'onStateChange': onStateChange
                }
            });
        });
    });
};

var tag = document.createElement('script');
tag.src = "//www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);